package com.kkw.shoppingmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.kkw.common.constant.ProductConstant;
import com.kkw.common.to.SkuEsModel;
import com.kkw.common.to.SkuHasStockVo;
import com.kkw.common.to.SkuReductionTO;
import com.kkw.common.to.SpuBoundTO;
import com.kkw.common.utils.R;
import com.kkw.shoppingmall.product.feign.CouponFeignService;
import com.kkw.shoppingmall.product.entity.*;
import com.kkw.shoppingmall.product.feign.SearchFeignService;
import com.kkw.shoppingmall.product.feign.WareFeignService;
import com.kkw.shoppingmall.product.service.*;
import com.kkw.shoppingmall.product.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.kkw.shoppingmall.product.dao.SpuInfoDao;
import com.kkw.common.utils.PageUtils;
import com.kkw.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    /**
     * feign 远程调用优惠券服务
     */
    @SuppressWarnings("all")
    @Autowired
    private CouponFeignService couponFeignService;
//
    @SuppressWarnings("all")
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @GlobalTransactional 不是高并发场景可以使用  at模式  要代理数据源后才能使用
     * @param vo
     */
//    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1.保存spu基本信息 pms_sku_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(vo, spuInfoEntity);
        this.saveBatchSpuInfo(spuInfoEntity);
        // 2.保存spu的表述图片  pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        // String join 的方式将它们用逗号分隔
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        // 3.保存spu的图片集  pms_sku_images

        // 先获取所有图片
        List<String> images = vo.getImages();
        // 保存图片的时候 并且保存这个是那个spu的图片
        spuImagesService.saveImages(spuInfoEntity.getId(), images);
        // 4.保存spu的规格属性  pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            // 可能页面没用传入属性名字 根据属性id查到所有属性 给名字赋值
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);
        // 5.保存当前spu对应所有sku信息 shoppingmall_sms->sms_spu_bonds
        Bounds bounds = vo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTO);
        spuBoundTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTO);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
        // 1).spu的积分信息 sms_spu_bounds
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            // 提前查找默认图片
            skus.forEach(item -> {
                String dufaultImg = "";
                for (Images img : item.getImages()) {
                    if (img.getDefaultImg() == 1) {
                        dufaultImg = img.getImgUrl();
                    }
                }
                // 2).基本信息的保存 pms_sku_info
                // skuName 、price、skuTitle、skuSubtitle 这些属性需要手动保存
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                // 设置spu的品牌id
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount((long) (Math.random() * 2888));
                skuInfoEntity.setSkuDefaultImg(dufaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                // 3).保存sku的图片信息  pms_sku_images
                // sku保存完毕 自增主键就出来了 收集所有图片
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity ->
                        // 返回true就会保存 返回false就会过滤
                        !StringUtils.isEmpty(entity.getImgUrl())
                ).collect(Collectors.toList());

                skuImagesService.saveBatch(imagesEntities);

                // 4).sku的销售属性  pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    // 对拷页面传过来的三个属性
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 5.) sku的优惠、满减、会员价格等信息  [跨库]
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                if (skuReductionTO.getFullCount() > 0 || (skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) > 0)) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTO);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBatchSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = null;
        try {
            QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
            String key = (String) params.get("key");
            if (StringUtils.isNotBlank(key)) {
                queryWrapper.and(item -> {
                    item.eq("id", key).or().like("spu_name", key);
                });
            }
            //status=1 and id=1 or spu_name like xxx 这样的写法是有问题的 二选一就必须使用and
            //status=1 and (id=1 or spu_name like xxx)
            String status = (String) params.get("status");
            if (StringUtils.isNotBlank(status)) {
                queryWrapper.eq("publish_status", status);
            }
            String brandId = (String) params.get("brandId");
            if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
                queryWrapper.eq("brand_id", brandId);
            }
            String catelogId = (String) params.get("catalogId");
            if (StringUtils.isNotBlank(catelogId)&& !"0".equalsIgnoreCase(catelogId)) {
                queryWrapper.eq("catalog_id", catelogId);
            }


            page = this.page(
                    new Query<SpuInfoEntity>().getPage(params),
                    queryWrapper
            );

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new PageUtils(page);

    }

    /**
     * 商品上架
     * @param spuId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void up(Long spuId) {
        try {
            //1、查出当前spuId对应的所有sku信息，能拿到品牌的名字等等
            List<SkuInfoEntity> skus=skuInfoService.getSkusBySpuId(spuId);
            //这些skuId对应的库存信息 给库存feign服务的
            List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

            //todo 4、查询当前sku的所有规格属性 这里只需要查询一遍即可 不用去stream流里面处理了
            List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);
            List<Long> attrIds = baseAttrs.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());

            List<SkuEsModel.Attrs> attrs = new ArrayList<>();
            //和上面的baseAttrs中进行对比得到 现在下面能够进行检索的集合值
            List<Long> searchAttrIds=attrService.selectSearchAttrIds(attrIds);
            Set<Long> idSet = new HashSet<>(searchAttrIds);

            List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
                //如果这个元素在这个set里面存在 则返回true 就会收集这个元素
                return idSet.contains(item.getAttrId());
            }).map(item -> {
                SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
                BeanUtils.copyProperties(item, attrs1);
                return attrs1;
            }).collect(Collectors.toList());

            Map<Long, Boolean> stockMap = null;
            try {
                //todo 1、发送远程调用，库存系统是否有库存查询  是否有库存
                R r = wareFeignService.getSkuHasStock(skuIdList);
                //以SkuId为key 是否有库存hashStock 为值
                TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
                };
                stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
            } catch (Exception e) {
                log.error("库存服务查询出现异常:原因：{}",e);
            }

            //2、封装每一个sku的信息
            Map<Long, Boolean> finalStockMap = stockMap;
            List<SkuEsModel> upProducts = skus.stream().map(sku -> {
                //组装需要的数据
                SkuEsModel esModel = new SkuEsModel();
                BeanUtils.copyProperties(sku,esModel);

                esModel.setSkuPrice(sku.getPrice());
                esModel.setSkuImg(sku.getSkuDefaultImg());

                //todo 2、热度评分 暂时设置为 0
                esModel.setHotScore(0L);
                //todo 3、查询品牌和分类的名字信息
                BrandEntity brand = brandService.getById(esModel.getBrandId());
                esModel.setBrandName(brand.getName());
                esModel.setBrandImg(brand.getLogo());
                CategoryEntity category = categoryService.getById(esModel.getCatalogId());
                esModel.setCatalogName(category.getName());

                //设置是否有库存
                if (finalStockMap ==null){
                    esModel.setHasStock(true);
                }else {
                    esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
                }
                //设置检索属性attrs
                esModel.setAttrs(attrsList);

                return esModel;
            }).collect(Collectors.toList());


            //todo 5、将数据发送的ES进行保存 shoppingmall-search
            R r = searchFeignService.productStatusUp(upProducts);
            if (r.getCode()==0) {
                //远程调用成功
                //todo 6、修改当前spu商品的状态
                this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
            }else {
                //todo 7、重复调用问题  即 幂等性问题 重试机制
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }


}